package cn.nc.service;


import cn.nc.entity.User;
import cn.nc.repository.RoleRepository;
import cn.nc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserRepository userRepository;


    @Autowired
    RoleRepository roleRepository;

    //UserDetailsService默认方法
    @Override
    public UserDetails loadUserByUsername(String s)throws UsernameNotFoundException {
        User user = userRepository.findByUsername(s);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }

    public boolean register(String email,String username,String password){
        if(userRepository.findByUsername(username)!=null) return false;
        else if(userRepository.findByEmail(email)!=null) return false;
        else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            User user = new User();
            user.setEmail(email);
            user.setUsername(username);
            user.setPath("0.jpg");
            user.setAddress(null);
            user.setSex("未知");
            user.setContent("妹东西捏");
            user.setAge(null);
            user.setPassword(encoder.encode(password));
            user.setRoles(Arrays.asList(roleRepository.findById(2).get()));
            System.out.println(user);
            userRepository.save(user);
            return true;
        }
    }

}
